package com.kind.perm.core.account.service.impl;

import com.kind.common.exception.ServiceException;
import com.kind.common.persistence.PageQuery;
import com.kind.common.persistence.PageView;
import com.kind.perm.core.account.dao.AccountDao;
import com.kind.perm.core.account.domain.AccountDO;
import com.kind.perm.core.account.service.AccountService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 
 * 用户管理业务处理实现类. <br/>
 *
 * @date:2016年12月12日 <br/>
 * @author 李明
 * @version:
 * @since:JDK 1.7
 */
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountDao accountDao;

	@Override
	public PageView<AccountDO> selectPageList(PageQuery pageQuery) {
        pageQuery.setPageSize(pageQuery.getPageSize());
		List<AccountDO> list = accountDao.page(pageQuery);
		int count = accountDao.count(pageQuery);
        pageQuery.setItems(count);
		return new PageView<>(pageQuery, list);
	}



	@Override
	public int save(AccountDO entity) throws ServiceException {
		try {
		  return accountDao.saveOrUpdate(entity);

        }catch (Exception e){
		    e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }

	}

	@Override
	public AccountDO getById(Long id) {
		return accountDao.getById(id);
	}

    @Override
    public void remove(Long id) throws ServiceException{
        try {
			accountDao.remove(id);

        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
    }
    


	@Override
	public AccountDO saveOrUpdateByOpenId(AccountDO entity) {
		// TODO Auto-generated method stub
		AccountDO openId = new AccountDO();
		openId.setOpenId(entity.getOpenId());
		List<AccountDO> openIdList = accountDao.queryList(openId);
		if(openIdList!=null&&openIdList.size()>0){
			entity.setId(openIdList.get(0).getId());
			entity.setLastLoginTime(new Date());
		}else{
			entity.setRegisterDate(new Date());
		}
		accountDao.saveOrUpdate(entity);
		openIdList = accountDao.queryList(openId);
		openIdList.get(0).setHeadImage(entity.getHeadImage());
		return openIdList.get(0);
	}
	
	@Override
	public List<AccountDO> queryList(AccountDO entity) {
		return accountDao.queryList(entity);
	}
}
